# -----------------------------------------------------------------------------
#     G N U    M A K E   S C R I P T   S P E C I F I C A T I O N
# -----------------------------------------------------------------------------
# NAME
#
#  Makefile  - GNU Makefile to build GCE Programming Book.
#
# REVISION HISTORY
#     11/16/2012   T.J. Yang init.
#
# USAGE
#       gmake : to make main tex book file.
#       gmake upload: to make and upload generated pdf file to tmp directory.
#       gmake [status|push]
# DESCRIPTION
# target1 target2 target3 : prerequisite1 prerequisite2  prerequisite3
#         command 1
#         command 2
# $< : The filename of the first prerequisite.
# $@ : The filename representing the target
# $< : The filename of the first prerequsite.
# $? : The names of all prequisites that are newer than the target,
#      separated by spaces.
# $^ : The filnames of all the prerequisites,separted by spaces.
# $+ : Similar to $^, this i sthe names of all the prerequisites
# separated by spaces.
# $* : The stem of the target filname. A stem is typically a filname
# without its suffix.
# 
# TODOs
#  1. Improve Makefile syntax.
# ---------------------------- CONSTANT DECLARATION ---------------------------
DES=This is a collection of open source documents regarding to libreswan and  published as book format using LaTeX.
# Sub Makefile directories for other tasks.
#SUBDIRS := fig dia tab creative_commons metapost pic
SUBDIRS := dia svg
RM :=/bin/rm
CP :=/bin/cp
GIT:=/usr/bin/git
ASPELL :=/usr/bin/aspell
SORT :=/usr/bin/sort
AWK :=/usr/bin/awk
PR  :=/usr/bin/pr
PERL:=/usr/bin/perl
BOOKNAME=libreswan
sources := \
	libreswan.tex \
	99book.bib \
	99defs.tex \
	build-id.tex \
        title.tex \
	preface.tex \
	doc.tex \
        software2software.tex \
        software2hardware.tex \
        development.tex \
        debugging.tex \
	bookmaking.tex \
	license.tex
#        tww-sbutils.tex \
# define the srouce files to generate images.
image-sources := ClusterWAN.dia 

# ---------------------------- VARIABLES  DECLARATION ---------------------------
# (filter, matched pattern,filenames)
image-dot := $(filter %.dot,$(image-sources))
image-svg := $(filter %.svg,$(image-sources))
image-png := $(filter %.png,$(image-sources))
image-dia := $(filter %.dia,$(image-sources))
# what  is this ?
image-pdf  := $(image-dot:%.dot=%.pdf) $(image-svg:%.svg=%.pdf) $(image-png) 
#image-pdf  := $(image-dot:%.dot=%.pdf) 
image-html := $(image-dot:%.dot=%.png) $(image-svg:%.svg=%.png) $(image-png)
image-dia  := $(image-dia:%.dia=%.pdf)

example-prereqs := /usr/bin/merge

dist-sources := \
	../html/hgicon.png \
	../html/index.html.var \
	../html/index.en.html

latex-options = \
	-interaction batchmode \
	-output-directory $(dir $(1)) \
	-jobname $(basename $(notdir $(1)))

latex-options-verbose = \
	-output-directory $(dir $(1)) \
	-jobname $(basename $(notdir $(1)))

# change this to git
hg = $(shell which hg)
hg-id = $(shell hg parents --template '{node|short}, dated {date|isodate},\n')
hg-version = $(shell hg version -q | \
	     sed 's,.*(version \(unknown\|[a-f0-9+]*\)),\1,')


# git log --pretty=format:'%h' -n 1
# git log -1 --format="%H%"
GIT :=$(shell which git)
git-version :=$(shell git log --pretty=format:'%h' -n 1)
XELATEX :=$(shell which xelatex)

# ------------------------- MAKEFILE MACROS  ---------------------------

# WHAT: To upload BOOKNAME.pdf onto code.google.com/p/libreswan
#  WHY: Automation
GUPLOAD=bin/googlecode_upload.py -p libreswan
define upload2google
	cd pdf;../${GUPLOAD} -s $1 $2
endef

# WHAT: pdf funtion to create final book pdf file into pdf dir
# HOW: 
#    1. create pdf directory
#    2. use pdflatex to run BOOKNAME.tex remove pdf/BOOKNAME.pdf if error=1
#    3. copy 99book.bib that needed for bibargph reference.
#    4. run bibtex after 99book.bib is copyied
#    5. run makeindex for  creating index pages.
#    6. run pdflatex twice
#    7  if "Reference.*undefined" is found in BOOKNAME.log file 
#       then failed pdf creation with return code 1
define pdf
 mkdir -p $(dir $@)
 TEXINPUTS=$(dir $<): pdflatex $(call latex-options,$@) $< || (rm -f $@; exit 1)
 cp 99book.bib $(dir $@)
 cd $(dir $@) && bibtex $(basename $(notdir $@))
 cd $(dir $@) && makeindex $(basename $(notdir $@))
 TEXINPUTS=$(dir $<): pdflatex $(call latex-options,$@) $< || (rm -f $@; exit 1)
 TEXINPUTS=$(dir $<): pdflatex $(call latex-options,$@) $< || (rm -f $@; exit 1)
 if grep 'Reference.*undefined' $(@:.pdf=.log); then echo "failed";exit 1; fi
endef

# WHAT: Generate BOOKNAME.tex into html files macro
# This is a horrible hack to work around the fact that the htlatex
# command in tex4ht is itself a horrible hack.  I really don't want to
# include verbatim the big wad of TeX that is repeated in that script,
# but I've given up and run a hacked copy as htlatex.book here.
define htlatex
 mkdir -p $(dir $(1))
 cp 99book.bib $(dir $(1))
 TEXINPUTS=$(dir $(2)): ./htlatex.book $(2) "bookhtml,html4-uni,$(3)" " -cunihtf -utf8" "$(dir $(1))" "$(call latex-options,$(1))" || (rm -f $(1); exit 1)
 cd $(dir $(1)) && tex4ht -f/$(basename $(notdir $(1))) -cvalidate -cunihtf
 cd $(dir $(1)) && t4ht -f/$(basename $(notdir $(1)))
 ./fixhtml.py $(dir $(1))/*.html
 rm $(dir $(1))/xymon-rtfm.css
endef


# ------------------------- MAKEFILE TARGETS  ---------------------------
all: Makefile diagram pdf 
#all: pdf html 
#all: html 

pdf: pdf/${BOOKNAME}.pdf

diagram:
	@for d in $(SUBDIRS); \
        do                 \
            $(MAKE) --directory=$$d;   \
        done

pdf/${BOOKNAME}.pdf: $(sources)  
	$(call pdf)

gupload:
	$(call upload2google,"${DES}",${BOOKNAME}.pdf)

html: onepage split

# onepage: $(htlatex) html/onepage/xymon-rtfm.html html/onepage/xymon-rtfm.css $(image-html:%=html/onepage/%)

html/onepage/%: %
	cp $< $@

# split: $(htlatex) html/split/xymon-rtfm.html html/split/xymon-rtfm.css $(image-html:%=html/split/%)

html/split/%: %
	cp $< $@


html/onepage/xymon-rtfm.html: $(sources) $(image-html) examples bookhtml.cfg
	$(call htlatex,$@,$<)

html/split/xymon-rtfm.html: $(sources) examples bookhtml.cfg
	$(call htlatex,$@,$<,2)

%.tex: %.html
	html2latex $@ $<

# Produce 90dpi PNGs for the web.

%.png: %.svg
	inkscape -D -e $@ $<

%.svg: %.dot
	dot -Tsvg -o $@ $<


# Produce eps & pdf for the book pdf
# % stem of a file name.
# $< : The filename of the first prerequsite.
%.eps: %.svg
	inkscape -E $@ $<

%.eps: %.dot
	dot -Tps -o $@ $<

%.eps: %.dia
	dia -t eps $< 
%.pdf: %.eps
	epstopdf  $<

examples: $(example-prereqs) examples/.run

examples/.run: $(example-sources:%=examples/%.run)
	touch examples/.run

examples/%.run: examples/% examples/run-example
	cd examples && ./run-example $(notdir $<)

changelog := $(wildcard ../.hg/store/00changelog.[id])
ifeq ($(changelog),)
changelog := $(wildcard ../.hg/00changelog.[id])
endif

build-id.tex: $(changelog)
	echo -n '$(hg-id)' > build-id.tex

hg_id.tex: $(hg)
	echo -n '$(hg-version)' > hg_id.tex

git_id.tex: $(GIT)
	echo -n '$(git-version)' > git_id.tex
clean: 
	rm -rf dist html

install: pdf split $(dist-sources)
	rm -rf dist
	mkdir -p dist
	cp pdf/${BOOKNAME}.pdf dist
	cp html/split/*.{css,html,png} dist
	cp $(dist-sources) dist

rsync: install
	rsync -avz --delete dist sp.red-bean.com:public_html/xymon-rtfm

upload: all 
	sudo rsync -avz --delete pdf/*.pdf  /var/www/html/books
#	sudo rsync -avz --delete html   /var/www/html/books/
tar: 
	tar czvf /tmp/hobbit-rtfm.tgz  /home/tjyang/docs/hobbit-rtfm
	sudo rsync -avz --delete /tmp/*.tgz /var/www/html/pdf

dia:
	dia -t eps xymon-daemons.dia 
	epstopdf xymon-daemons.eps
movetmp: 
	sudo rsync -avz --delete pdf/*.pdf  ~tjyang/tmp

# $@ : The filename representing the target
# $< : The filename of the first prerequisite.
check: libreswan.tex
	pdflatex  $(call latex-options-verbose,pdf/libreswan.pdf) $< 

check2: tex-samples/xetex-sample.tex
	${XELATEX}  --output-directory=./pdf $<

gitpush:
	( $(GIT) commit -a -m "makefile update" )
	( $(GIT) push origin master )
gitpull: 
	( $(GIT) pull )
